/*******************************************************************************
 * Copyright 2010 DemandSpot
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.demandspot.utils;

import java.util.Random;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;

public class RandomUtils {

	private static String CODE_SET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
	private static int BASE = CODE_SET.length();
	
	public static String randomHash() {
		return DigestUtils.md5Hex(uuid());
	}
	
	public static String uuid() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}
	
	public static String password(int length) {
		StringBuffer buffer = new StringBuffer();
		Random random = new Random();		
		
		char[] chars = CODE_SET.toCharArray();
		for (int i = 0; i < length; i++) {
			buffer.append(chars[random.nextInt(chars.length)]);
		}
		return buffer.toString();
	}
	
	public static String shorten(Long number) {
		if (number == null || number < 1) {
			return "";
		}
		StringBuilder converted = new StringBuilder();
		while (number > 0) {
			converted.insert(0, CODE_SET.charAt((int)(number % BASE)));
			number /= BASE; 
		}
		return converted.toString();
	}
	
	public static Long expand(String compressed) {
		if (compressed == null || compressed.isEmpty()) {
			return 0l;
		}
		long res = 0;
		for (int i = compressed.length(); i > 0; i--) {
			int k = i - compressed.length();
			res += Math.pow(BASE, i-1) * CODE_SET.indexOf(compressed.charAt(-k)); 
		}		
		return res;
	}	
	
}
